package CMobile
{
	import UIFree.ObjectEvent;
	
	import api_servers.pi_servers;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	public class pm_mobile extends Object {
		private var _app: Object;
		private var _dialog: Object;
		private var _preview: pm_result;
		private var _sizeInput: Object;
		private var _cardInfo: Object;
		private var _dataLoader: URLLoader;
		
		protected const BUTTONTITLE: String = 'Скачать как фон для сотового телефона';
		protected const DESCRIPTION: String = 'Вы можете загрузить открытку в виде фона для сотового телефона. В правой части этого диалога выберите модель вашего телефона. Открытка автоматически адаптируется под разрешение экрана вашего телефона. Вы можете в поле «Разрешение экрана» ввести другие значения, если в списке нет вашего телефона.';
		protected const TITLE: String 		= 'Фон для сотового телефона';
		protected const PRODUCER: String	= 'Производитель вашего телефона';
		protected const MODELPHONE: String	= 'Модель телефона';
		protected const RESOLUTION: String	= 'Разрешение экрана';
		protected const PREVIEW: String		= 'Предпросмотр';
		protected const WARNING: String 		= 'Внимание!';
		protected const UNDEFINESIZE: String 	= 'Неправильно задан параметр «Разрешение экрана». Выберите производителя и модель вашего телефона, либо введите разрешение вручную, например: 240 x 320.';
		
		
		public function pm_mobile(a_app: Object, dispatcher: EventDispatcher) {
			super();
			_app = a_app;
			_dataLoader = new URLLoader(new URLRequest(pi_servers.ADDR[2] + '/games/data/phones.xml'));
			_dataLoader.addEventListener(Event.COMPLETE, function(e: Event): void {
				createDialog(new XML(e.target.data));
			});
			dispatcher.addEventListener('PLUGINBTRELEASE', showDialog);
		}
		
		protected function activateDialog(): void {
			resetPhoto(_sizeInput.text);
			_dialog.show();
		}
		
		protected function showDialog(e: ObjectEvent): void {
			if (_dialog) activateDialog();
			else if (!_dataLoader.data) {
				_dataLoader.addEventListener(Event.COMPLETE, function(e: Event): void {
					activateDialog();
				})
			}
		}
		
		protected function parseSize(sizeString: String): Point {
			var resSize: Array = sizeString.split('x');
			if (resSize.length > 0) {
				if (resSize.length == 1) resSize[1] = resSize[0];
				var res: Point = new Point(parseFloat(resSize[0]), parseFloat(resSize[1]));
				if (res.length > 1000) res.normalize(1000);
				return res;
			} else return new Point();
		} 
		
		protected function resetPhoto(sizeString: String): void {
			var l_size: Point = parseSize(sizeString); 
			if (_app.editor && _app.editor.cardBody && _app.editor.cardBody.loaded) _preview.reset(_app.editor.cardBody.bitmap, l_size.x, l_size.y);
		}
		
		protected function createDialog(xmlData : XML): void {
			_dialog = new _app.classes['window'](_app.layers[4], 0, 0, 520, 480, 'window', true, 1);
			_dialog.position = new Point((_app.width - _dialog.width) / 2, (_app.height - _dialog.height) / 2);
			_dialog.title.text = TITLE;
			
			var inner: Rectangle = _dialog.getInner();
			var _pLayer: Object = new _app.classes['component'](_dialog, inner.x, inner.y + 80, inner.width, inner.height);
			
			var desc: Object = new _app.classes['label'](_dialog, inner.x, inner.y, inner.width, 70, 'description');
			desc.text = DESCRIPTION; 

			inner = _pLayer.getInner();
			desc = new _app.classes['label'](_pLayer, inner.x, inner.y, 230, 45, 'm_desc');
			desc.text = PRODUCER; 
			desc = new _app.classes['label'](_pLayer, inner.x, inner.y + 180, 230, 45, 'm_desc');
			desc.text = MODELPHONE;
			desc = new _app.classes['label'](_pLayer, inner.x + 250, inner.y, 230, 45, 'm_desc');
			desc.text = RESOLUTION;
			desc = new _app.classes['label'](_pLayer, inner.x + 250, inner.y + 82, 230, 45, 'm_desc');
			desc.text = PREVIEW;
			
			var sizeLayer	: Object = new _app.classes['component'](_pLayer, inner.x + 260, inner.y + 28, 230, 42, 'list');
			_sizeInput = new _app.classes['input'](sizeLayer, 5, 5, 220, 30, 'slInput');
			_sizeInput.text = '200x200';
			_preview = new pm_result(_pLayer, inner.x + 260, inner.y + 110, 230, 238);
			 
			var list		: Object = new _app.classes['searchlist'](_pLayer, inner.x + 10, inner.y + 28, 230, 140, 'list');
			var p_list		: Object = new _app.classes['searchlist'](_pLayer, inner.x + 10, inner.y + 208, 230, 140, 'list');
			p_list.addEvent('SELECT', function(e: Event): void {
				_sizeInput.text = p_list.list[p_list.selectIndex].@resolution;
				resetPhoto(_sizeInput.text);
			});
			
			_sizeInput.addEvent(Event.CHANGE, function (e: Event): void {
				resetPhoto(e.target.text);
			}, _sizeInput.textField);
			
			
			list.addEvent('FILTER', function(e: ObjectEvent): void {
				var n: String = e.object.element.@producer.toLowerCase();
				var index: int = n.indexOf(e.object.word.toLowerCase());
				e.result = (index == 0)?true:(e.object.word=='');
			});
			
			p_list.addEvent('FILTER', function(e: ObjectEvent): void {
				var n: String = e.object.element.@name.toLowerCase();
				var index: int = n.indexOf(e.object.word.toLowerCase());
				e.result = (index == 0)?true:(e.object.word=='');
			});
			
			var arr: Array = new Array();
			for each (var item: XML in xmlData.phones) arr.push(item);
			
			list.attachList(arr, function(area : Object, item: Object, index: int): Object {
				var c_item: Object = new _app.classes['label'](area, 0, index * 20, 210, 20, 'listItem');
				c_item.text = item.@producer;
				c_item._data = item;
				return c_item;
			});

			list.addEvent('FILTERED', function(e: ObjectEvent): void {
				p_list.clearList();
			});
			
			list.addEvent('SELECT', function(e: Event): void {
				var p_arr: Array = new Array();
				for each (var item: XML in list.list[list.selectIndex].models) p_arr.push(item);
				p_list.clearList();
				p_list.attachList(p_arr, function(area : Object, item: Object, index: int): Object {
					var c_item: Object = new _app.classes['label'](area, 0, index * 20, 210, 20, 'listItem');
					c_item.text = item.@name;
					c_item._data = item;
					return c_item;
				});
			});
			
			var d_button: Object = new _app.classes['button'](_dialog, inner.x + inner.width - 80, inner.y + 445, 80, 30, 'button');
			d_button.text = 'Скачать';
			d_button.addEvent(MouseEvent.CLICK, function(e: Event): void {
				var l_size: Point = parseSize(_sizeInput.text);
				if ((!l_size.x) || (!l_size.y))
					_app.alert(WARNING, UNDEFINESIZE);
				else {
					_app.manager.saveJPG(_preview.asBytes());
				}//_app.dispatchEvent(new ObjectEvent('COLLECTFILERELEASE', _preview.asParams));
			});
			
			list.selectIndex = 115;
			p_list.selectIndex = 92;
		}		
		
/*		protected function initStyles(): void {
			_app.styles['m_desc'] = uif_draw.union(_app.styles['description'], {
				text_format: {
					font: 'arial',
					size: 12,
					bold: true
				}				
			});
			
			_app.styles['list'] = {
				line_width: 1,
				line_alpha: 0.5,
				rounds: 10,
				fill_color: 0xFFFFFF,
				fill_alpha: 1,
				buttonSize: 25,
				padding: 5,
				buttonClass: 'listButton',
				selectClass: 'listItemSelect',
				inputClass: 'slInput'
			}
			
			_app.styles['slInput'] = {
				line_width: 1,
				line_alpha: 0.5,
				margin: 5,
				text_format: {
					font: 'arial',
					size: 12
				}
			}
			
			_app.styles['listItem'] = {
				text_format: {
					font: 'arial',
					size: 11,
					wordWrap: true,
					color: 0x333444,
					multiline: true,
					selectable: false
				}
			}
			
			_app.styles['listItemSelect'] = uif_draw.union(_app.styles['listItem'], {
				fill_color: 0x0DD000,
				fill_alpha: 1,
				text_format: {
					color: 0xFFFFFF
				}
			})
			
			_app.styles['listButton'] = uif_draw.union(_app.styles['button'], {
				padding: 4,
				rounds: 0
			});
		}*/ 
	}
}